<template>
  <div class="page-mobile-quickpay">
    <div class="header-logo">
      <img :src="web_info.COMPANY_LOGO" alt="" />
    </div>
    <div class="main">
      <div class="breadcrumb">
        <span style="color:#999;">首页</span>
        <span>></span>
        <span>快捷支付</span>
      </div>
      <div class="main-container" v-if="!pay_success">
        <div class="order-wrapper">
          <div class="order-info">
            <div class="order-title">订单信息</div>
            <div class="order-list">
              <div class="order-list-item">订单SN：{{ orderInfo.orderSn }}</div>
              <div class="order-list-item">
                订单状态：{{
                  orderInfo.status == 1
                    ? "待缴费"
                    : orderInfo.status == 3
                    ? "已缴费"
                    : "已关闭"
                }}
              </div>
              <div class="order-list-item">
                创建时间：{{ trimDate(orderInfo.createTime) }}
              </div>
            </div>
          </div>
        </div>
        <div class="course-wrapper">
          <div class="course-title">
            <span>购买课程</span>
            <span>课程单价</span>
          </div>
          <div class="course-list">
            <div class="course-list-left">
              {{orderInfo.courseName}}
            </div>
            <div class="course-list-right">￥{{orderInfo.price}}</div>
          </div>
        </div>
        <div class="pay-wrapper">
          <div class="pay-left">支付方式</div>
          <div class="pay-right">
            <van-radio-group v-model="payType">
              <van-radio :name="1" v-if="orderPayType == 'all' || orderPayType == 'weixin'"
                ><div class="pay-option weixin">
                  <img src="/img/mobile/member_payment_wechat.png" alt="" />微信
                </div></van-radio
              >
              <br />
              <van-radio :name="2" :disabled="is_in_wechat" v-if="orderPayType == 'all' || orderPayType == 'zhifubao'"
                ><div class="pay-option zhifubao">
                  <img
                    src="/img/mobile/member_payment_alipay.png"
                    alt=""
                  />支付宝
                </div></van-radio
              >
            </van-radio-group>
            <p class="zfb-tips" v-if="is_in_wechat && (orderPayType == 'all' || orderPayType == 'zhifubao')">如需支付宝支付，请在浏览器中打开</p>
          </div>
        </div>
        <div class="text-info">
          <p>总金额：<span style="color:#FF0036">￥{{orderInfo.price}}</span></p>
          <p class="argee-art">
            <van-checkbox v-model="argeeArt" shape="square">同意</van-checkbox>
            <a href="javascript:void(0);" @click="toPath('/m/protocol')"
              >《购买协议》</a
            >
          </p>
        </div>
        <div class="pay-order">
          <span class="pay-text">应付款：</span>
          <span class="money">￥{{orderInfo.price}}</span>
          <span class="pay-btn" @click="handlePay()">支付订单</span>
        </div>
      </div>
      <div class="success-wrapper" v-if="pay_success">
        <van-icon name="checked" size="1rem" color="#19be6b" />
        <p>支付成功</p>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { baseUrl, socketUrl } from "~/config/conf";
// import secret from "../../utils/secret";
import { wxH5QuickPay,getPayOrderInfo,getQuickpayToH5Alipay,wxBrowserQuickPay,wxWechatQuickPay,wxAuthorizationQuickPay } from "~/api/quickpay";
import { wexinPay, wxJspay } from "~/utils/pay";
export default {
  name: "page-mobile-quickpay",
  data() {
    return {
      payType: 1,
      argeeArt: true,
      orderInfo: {},
      wechat_pay_qr: "",
      is_show_wechat_pay: false,
      pay_success: false,
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0 //socket重连计数器
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      web_info(state) {
        return state.web_info;
      },
      user_info(state) {
        return state.user_info;
      },
      theme_color(state) {
        return state.theme_color;
      },
      login_type(state) {
        return state.login_type;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
    }),
    orderId() {
      return this.$route.query.orderId;
    },
    orderSn() {
      return this.$route.query.orderSn;
    },
    orderPayType() {
      if(this.$route.query.payType == 'all' || this.$route.query.payType == 'weixin'){
        this.payType = 1;
      }else if(this.$route.query.payType == 'zhifubao'){
        this.payType = 2;
      }
      return this.$route.query.payType;
    },
    isWxAuthorization() {
      if(this.$route.query.isWxAuthorization){
        return true;
      }else{
        return false;
      }
    },
  },
  created() {
    this.getOrderInfo();
    this.initWebSocket();
    if(this.$route.query.isSuccess == 1){
      this.pay_success = true;
    }
  },
  mounted() {},
  deactivated() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  activated() {
    this.getOrderInfo();
    this.initWebSocket();
    if(this.$route.query.isSuccess == 1){
      this.pay_success = true;
    }
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    // 跳转链接
    toPath(path) {
      this.$router.push(path);
    },
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "payOrder/" + this.orderSn;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          // 付款成功
          this.pay_success = true;
          this.is_show_wechat_pay = false;
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    // 格式化时间
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        let add0 = m => {
          return m < 10 ? "0" + m : m;
        };
        return `${_date.getFullYear()}-${add0(_date.getMonth() + 1)}-${add0(
          _date.getDate()
        )}  ${add0(_date.getHours())}:${add0(_date.getMinutes())}:${add0(
          _date.getSeconds()
        )}`;
      } else {
        return "";
      }
    },
    // 获取订单信息
    async getOrderInfo() {
      if (this.orderSn) {
        let result = await getPayOrderInfo(this.orderSn);
        if (result && result.data && result.data.code == 200) {
          this.orderInfo = result.data.data;
        } else {
          this.$toast("网络波动，请稍后再试！");
        }
      }
    },
    // 支付订单
    async handlePay() {
      if (!this.argeeArt) {
        this.$toast("请先勾选购买协议！");
        return;
      }
      if (this.orderInfo.status == 2) {
        this.$toast("该订单已经关闭，请勿支付！");
        return;
      }
      if (this.orderInfo.status == 3) {
        this.$toast("该订单已经缴费，请勿重复支付！");
        return;
      }
      if (process.client) {
        //支付类型
        let payType = this.payType;
        //订单SN
        let orderSn = this.orderInfo.orderSn;
        // 1，微信支付 2，支付宝支付
        if (payType == 1) {
            //微信内置浏览器内
            if (this.is_in_wechat) {
                //判断是否已经微信授权
                if(this.isWxAuthorization){
                  let result = await wxBrowserQuickPay({orderSn});
                  if (result && result.data && result.data.code == 200) {
                      const { data } = result.data;
                      console.log(result);
                      console.log(
                      "=====================微信JS支付====================="
                      );
                      wxJspay(
                      data,
                      res => {
                          // this.pay_success = true;
                          console.log("微信JS支付结果：", res);
                      },
                      err => {
                          console.log(err);
                      }
                      );
                  } else {
                    this.$toast("调起失败");
                      // this.$toast(
                      // this.$t("locale.mobile.wallet.t24") + result &&
                      //     result.data &&
                      //     result.data.msg
                      // );
                  }
                }else{
                  // 进行微信授权
                  let result = await wxAuthorizationQuickPay({orderSn});
                  console.log("result:", result);
                  if (result.data.code == 200) {
                    window.location.href = result.data.msg;
                  } else {
                    this.$toast(this.$t("locale.mobile.login.t19"));
                  }
                }
                
            }else{
                console.log(
                    "=====================微信H5支付====================="
                );
                let result = await wxH5QuickPay({orderSn});
                if (result && result.data && result.data.code == 200) {
                    const { data } = result.data;
                    console.log(result);
                    window.location.href = `${
                    data.mweb_url
                    }&redirect_url=${encodeURIComponent(window.location.href)}`;
                } else {
                    this.$toast(
                    this.$t("locale.mobile.wallet.t24") + result.data
                        ? result.data.msg
                        : null
                    );
                }
            }
        } else if (payType == 2) {
            let result = await getQuickpayToH5Alipay(this.orderSn);
            console.log(result);
            if (result && result.data && result.data.code == 200) {
              window.location.href = result.data.data;
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + result.data
                  ? result.data.msg
                  : null
              );
            }
        }
      }
    }
  }
};
</script>
<style lang="scss">
.page-mobile-quickpay {
}
</style>
<style lang="scss" scoped>
.page-mobile-quickpay {
  width: 7.2rem;
  .header-logo {
    padding: 0.2rem;
    img {
      width: 4rem;
    }
  }
  .main {
    width: 7.2rem;
    .breadcrumb {
      padding: 0.2rem;
      width: 7.2rem;
      background: #f2f5fa;
      font-size: 0.2304rem;
    }
    .main-container {
      width: 7.2rem;
      .order-wrapper {
        width: 6.816rem;
        margin: 0.2rem auto;
        .order-title {
          background: #f2f5fa;
          border: 1px solid #dfe5ef;
          height: 0.8064rem;
          line-height: 0.8064rem;
          font-size: 0.3072rem;
          padding: 0px 0.2304rem;
        }
        .order-list {
          border-right: 1px solid #dfe5ef;
          border-left: 1px solid #dfe5ef;
          border-bottom: 1px solid #dfe5ef;
          color: #333;
          padding: 0.1344rem 0;
          .order-list-item {
            font-size: 0.3072rem;
            padding: 0.1152rem 0 0.1152rem 0.2304rem;
          }
        }
      }
      .course-wrapper {
        width: 6.816rem;
        margin: 0.6rem auto 0.2rem;
        .course-title {
          background: #f2f5fa;
          border: 1px solid #dfe5ef;
          height: 0.8064rem;
          line-height: 0.8064rem;
          font-size: 0.3072rem;
          padding: 0px 0.2304rem;
          display: flex;
          justify-content: space-between;
        }
        .course-list {
          display: flex;
          border-right: 1px solid #dfe5ef;
          border-left: 1px solid #dfe5ef;
          border-bottom: 1px solid #dfe5ef;
          color: #333;
          padding: 0.1344rem 0;
          justify-content: space-between;
          .course-list-left {
            width: 4.8rem;
            font-size: 0.3072rem;
            padding: 0.1152rem 0 0.1152rem 0.2304rem;
            word-break: break-word;
          }
          .course-list-right {
            width: 2rem;
            text-align: center;
            font-size: 0.3072rem;
            padding: 0.1152rem 0 0.1152rem 0.2304rem;
          }
        }
      }
      .pay-wrapper {
        width: 6.816rem;
        margin: 0.2rem auto 0.2rem;
        font-size: 0.3072rem;
        padding: 0 0.5376rem;
        display: flex;
        .pay-left {
          padding-right: 0.4rem;
          line-height: 0.7488rem;
        }
        .pay-right {
            .zfb-tips{
                margin-top: .1rem;
                color: #ff0036;
                font-size: .2304rem;
            }
          .pay-option {
            border-radius: 0.0768rem;
            display: flex;
            align-items: center;
            padding: 0.1rem 0.2112rem;
            img {
              width: 0.48rem;
              height: 0.48rem;
              display: block;
            }
            &.weixin {
              border: 1px solid #00c800;
            }
            &.zhifubao {
              border: 1px solid #2194d3;
            }
          }
        }
      }
      .text-info {
        font-size: 0.3072rem;
        text-align: right;
        width: 6.816rem;
        margin: 0.5rem auto 0.2rem;
        padding: 0 0.5376rem;
        a {
          color: #2194d2;
          text-decoration: none;
        }
        p {
          margin-bottom: 0.1rem;
        }
        .argee-art {
          display: flex;
          justify-content: flex-end;
        }
      }
      .pay-order {
        font-size: 0.3072rem;
        width: 6.816rem;
        margin: 0.5rem auto 0.2rem;
        padding: 0.2304rem;
        background: #f2f5fa;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .money {
          font-size: 0.4608rem;
          color: #ff0036;
        }
        .pay-btn {
          display: inline-block;
          padding: 0.096rem 0.384rem;
          color: #fff;
          border: none;
          outline: none;
          background: #ff0036;
          margin-left: 0.192rem;
          border-radius: 0.0768rem;
          cursor: pointer;
          font-size: 0.3072rem;
          height: 0.7296rem;
          line-height: 0.5376rem;
        }
      }
    }
    .success-wrapper {
      width: 6.816rem;
      margin: 1rem auto;
      background: #fff;
      text-align: center;
      p {
        font-size: 0.4rem;
        margin-top: 0.2rem;
      }
    }
  }
}
</style>
